from rest_framework import serializers

from ERP_5.utils.get_inventory import get_inventory_by_goods
from goods_info.models import GoodsModel
from production_info.models import BomProcessModel, BomMaterialModel


class ProcessSerializer(serializers.ModelSerializer):
    """
    生产工序的 序列化器
    """

    class Meta:
        model = BomProcessModel
        fields = '__all__'


class MaterialSerializer(serializers.ModelSerializer):
    """
    生产物料的 序列化器
    """
    cur_inventory = serializers.SerializerMethodField(read_only=True, help_text='在仓库中库存')

    class Meta:
        model = BomMaterialModel
        fields = '__all__'

    def get_cur_inventory(self, obj: BomMaterialModel):  # 当前的obj为：BomMaterialModel
        result = get_inventory_by_goods(obj.goods.id)
        return result if result else 0

class GoodsBomSerializer(serializers.ModelSerializer):
    """
    某一个货品的BOM表数据  序列化器
    """
    # 当前商品BOM表中所有的： 生产工序列表
    process_list = ProcessSerializer(many=True, read_only=True)

    # 当前商品BOM表中所有的： 生产物料列表
    material_list = MaterialSerializer(many=True, read_only=True)

    class Meta:
        model = GoodsModel
        fields = ['number_code', 'name', 'material_list', 'process_list']